package com.songcha.module_mine.ui.activity.userinfo

import android.app.Application
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.songcha.library_base.interfaces.IApiResult
import com.songcha.library_base.mvvm.base.BaseViewModel
import com.songcha.library_base.mvvm.base.beanFlatMap
import com.songcha.library_business.api.ApiManager
import com.songcha.library_business.bean.user.UserInfoBean
import com.songcha.library_business.event.user.LogoutEvent
import com.songcha.library_business.provider.ILogoutProvider
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_mine.bean.OssParamsBean
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.UUID


class UserInfoViewModel(app: Application):BaseViewModel<UserInfoRepository>(app) {
    var apiState=MutableLiveData<Boolean>()

    fun uploadAvatar(file: File){
        if(file.length()>1024*1024){
            ToastUtil.show("图片大小不能大于1M")
            return
        }

        handleApiDataObserver(repository!!.getOssParams(),object :IApiResult<OssParamsBean>{
            override fun onSuccess(bean: OssParamsBean) {
                uploadOssFile(file,bean.data)
            }

            override fun onError(e: Throwable) {

            }

        })

        /*val body=file.asRequestBody("multipart/form-data".toMediaTypeOrNull())

        val multipartBody = MultipartBody.Builder()
            .addFormDataPart("file", "file.jpg", body)
            .setType(MultipartBody.FORM)
            .build()
        val obs=MineApiManager.api.uploadFile(multipartBody.parts)
            .beanFlatMap { t->
                if(t.data.url.size>0){
                    return@flatMap repository!!.modifyUserAvatar(t.data.url[0],UserInfoManager.userInfo!!.id)
                }else{
                    return@flatMap Observable.error(JsonParseException())
                }

            }.beanFlatMap {t->
                ApiManager.api.getUserInfo()
            }

        handleApiDataObserver(obs,object :IApiResult<UserInfoDataBean>{
            override fun onSuccess(bean: UserInfoDataBean) {
               // bean as UpLoadFileDataBean
                UserInfoManager.saveUserInfo(bean.data)
                apiState.value=true
            }

            override fun onError(e: Throwable) {
                apiState.value=false
            }

        })*/

    }

    fun uploadOssFile(file: File,ossParams: OssParamsBean.DataBean){
        val uuid=UUID.randomUUID().toString()

        val credentialProvider: OSSCredentialProvider =
            object : OSSCustomSignerCredentialProvider() {
                override fun signContent(content: String?): String? {
                    if(content==null) return null
                    val c = repository!!.getOssSign(content)
                    val ret = c.blockingFirst().data
                    return ret
                   /* val response = c.execute()
                    return response.body()!!.data*/
                   // return OSSUtils.sign(ossParams.accessid,"Ei5l8THTcsnCTyXuj3I1rEFiyD0lYY",content)
                }
            }


        val oss = OSSClient(LibraryCommon.getContext(), "https://"+ossParams.endpoint, credentialProvider)


// 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件完整路径（例如/storage/emulated/0/oss/examplefile.txt）。
// Object完整路径中不能包含Bucket名称。
        // 构造上传请求。
// 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件完整路径（例如/storage/emulated/0/oss/examplefile.txt）。
// Object完整路径中不能包含Bucket名称。
        val put = PutObjectRequest(
            ossParams.bucket,
            ossParams.dir+uuid+".jpg",
            file.absolutePath
        )
// 异步上传时可以设置进度回调。
        put.progressCallback =
            OSSProgressCallback<PutObjectRequest?> { request, currentSize, totalSize ->
                Log.d(
                    "PutObject",
                    "currentSize: $currentSize totalSize: $totalSize"
                )
            }


        val task: OSSAsyncTask<PutObjectResult> = oss.asyncPutObject(
            put,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    //Log.d("PutObject", "UploadSuccess")
                    //Log.d("ETag", result.eTag)
                    //Log.d("RequestId", result.requestId)

                    val url="https://"+ossParams.bucket+"."+ossParams.endpoint+"/"+ossParams.dir+uuid+".jpg"
                    //LogUtil.log("上传成功",url)

                    modifyAvatar(url)

                }

                override fun onFailure(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException,
                    serviceException: ServiceException
                ) {
                    ToastUtil.show("222："+clientExcepion.message +","+serviceException.message)
                    // 请求异常。
                    if (clientExcepion != null) {
                        clientExcepion.printStackTrace()
                    }
                    if (serviceException != null) {
                        Log.e("ErrorCode", serviceException.errorCode)
                        Log.e("RequestId", serviceException.requestId)
                        Log.e("HostId", serviceException.hostId)
                        Log.e("RawMessage", serviceException.rawMessage)
                    }
                }
            })


        task.waitUntilFinished()

    }

    fun modifyAvatar(url:String){
        val obs=repository!!.modifyUserAvatar(url,UserInfoManager.userInfo!!.id)
            .beanFlatMap {
                return@beanFlatMap ApiManager.api.getUserInfo()
            }

        handleApiDataObserver(obs,object :IApiResult<UserInfoBean>{
            override fun onSuccess(bean: UserInfoBean) {
                UserInfoManager.saveUserInfo(bean.data)
                apiState.value=true
            }

            override fun onError(e: Throwable) {
                apiState.value=false
            }

        })
    }

    fun modifyNickName(nickName:String,userId:Int){
        val obs=repository!!.modifyUserNickName(nickName,userId)
            .beanFlatMap {
                return@beanFlatMap ApiManager.api.getUserInfo()
            }

        handleApiDataObserver(obs,object :IApiResult<UserInfoBean>{
            override fun onSuccess(bean: UserInfoBean) {
                UserInfoManager.saveUserInfo(bean.data)
                apiState.value=true
            }

            override fun onError(e: Throwable) {
                apiState.value=false
            }
        })
    }


    fun logout(){
        UserInfoManager.clearLogin()
        EventBus.getDefault().post(LogoutEvent())
        ARouter.getInstance().build("/task/DailyTaskController").navigation()?.let {
            (it as ILogoutProvider).onLogout()
        }
    }
}